package cn.wolfcode.cloud.shop.filter;

import cn.wolfcode.cloud.shop.feign.UserFeignApi;
import cn.wolfcode.cloud.shop.resp.Result;
import cn.wolfcode.cloud.shop.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author Administrator
 */
@Component
public class CookieRefreshFilter extends ZuulFilter {

    @Autowired
    private UserFeignApi userFeignApi;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Cookie cookie = CookieUtil.getCookie(request,CookieUtil.TOKEN_IN_COOKIE_NAME);
        return cookie != null;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        Cookie cookie = CookieUtil.getCookie(request,CookieUtil.TOKEN_IN_COOKIE_NAME);
        //redis刷新
        String token = cookie.getValue();
//        System.out.println(token);
        Result<Boolean> result = userFeignApi.refreshToken(token);
        if(result == null || result.hasError()){
            return null;
        }
        Boolean refreshed = result.getData();
        if(refreshed){
            CookieUtil.addCookie(response,CookieUtil.TOKEN_IN_COOKIE_NAME,token);
        }
        return null;
    }
}
